package org.jma.app.ewisdom.services.utils.queries;

import java.util.HashMap;
import java.util.Vector;

import org.jma.app.ewisdom.services.utils.LuceneIndexer;
import org.jma.app.ewisdom.services.utils.ScoreDocs;
import org.jma.lib.soap.sessions.SOAPSession;

import rice.p2p.commonapi.NodeHandle;
import easypastry.cast.CastContent;
import easypastry.cast.CastHandler;
import easypastry.cast.CastListener;
import easypastry.core.PastryKernel;

/**
 * QueryReceiver listens for the reception of a castContent, in this case a GlobalQuery
 * if the GlobalQuery object does not have a result, supposes that it's a query received, 
 * then executes the query, updates the result and send it to its sender. In case that result is not null
 * supposes that it is a response of a query then it stores the pair &lt;queryName,quey&gt; into a hashMap
 * of queries.<br>
 * This Object is designed to be stored into a {@link SOAPSession}.
 * @author jesmari@ono.com
 * @version 1.0
 * @since 1.0
 */
public class QueryReceiver implements CastListener {

	HashMap queries=new HashMap();
	String group;
	
	public QueryReceiver(String group){
		this.group=group;
	}

	public boolean contentAnycasting(CastContent content) {
		contentDelivery(content);
		return true;
	}

	public void contentDelivery(CastContent content) {
		GlobalQuery gq =(GlobalQuery)content;
		String query=gq.getQuery();
		if (gq.getResult()==null){
			LuceneIndexer lind;
			try {
				lind = new LuceneIndexer();
				ScoreDocs result=(ScoreDocs)lind.doQuery(query);
				//Sends response
				((GlobalQuery)content).setResult(result);
				CastHandler cast = PastryKernel.getCastHandler();
				cast.subscribe(group);
				NodeHandle node = content.getSource();       
				cast.sendDirect(node, content);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else{
			QueryVector q=(QueryVector)queries.get(gq.getQuery());
			if (q==null){ 
				q=new QueryVector();
				queries.put(gq.getQuery(), q);
			}
			q.add(gq);
		}
	}
	
	public void removeQuery(String queryName){
		queries.remove(queryName);
	}
	
	public QueryVector getQuery(String queryName){
		return (QueryVector)queries.get(queryName);
	}
	
	
	public void hostUpdate(NodeHandle nh, boolean joined) {
        if (joined){
            System.out.println("Global search listener  Node join : "+nh);
        }
        else System.out.println("Global search listener  Node leave : "+nh);
	}
	

}
